<?php

namespace App\Http\Controllers\Admin\System;

use App\Enums\ResponseEnum;
use App\Http\Controllers\AdminController;
use App\Models\System\DicGroup;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DicGroupController extends AdminController
{
    public function data()
    {
        $list = DicGroup::query()->select(['id', 'parent_id as parentId', 'name', 'code'])->get()->toArray();
        return $this->succeed($list);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required','max:50'],
            'code' => ['required','max:90','unique:system_dic'],
        ]);
        $data = $request->only(['parent_id', 'name', 'code']);
        DB::beginTransaction();
        try {
            $model = DicGroup::query()->create([
                'parent_id' => (int)$data['parent_id'],
                'name' => $data['name'],
                'code' => $data['code']
            ]);
            $this->createSyslog('添加了一条字典分类记录', $data, $model);
            DB::commit();
            return $this->succeed([
                'id' => $model['id'],
            ]);
        }catch (\Exception) {
            DB::rollBack();
        }
        return $this->fail();
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => ['required','max:50'],
            'code' => ['required','max:90','unique:system_dic,code,'.$id.',id'],
        ]);
        $model = DicGroup::query()->findOrFail($id);
        $data = $request->only(['parent_id', 'name', 'code']);
        DB::transaction(function () use ($model, $data) {
            $model->update([
                'parent_id' => (int)$data['parent_id'],
                'name' => $data['name'],
                'code' => $data['code']
            ]);
            $this->createSyslog('更新了一条字典分类记录', $data, $model);
        });
        return $this->succeed();
    }

    public function destroy(Request $request)
    {
        $request->validate(['ids' => ['required','array','max:'.static::QUERY_LIMIT]]);
        $ids = $request->get('ids');
        abort_if(in_array(1, $ids, true), ResponseEnum::ROLE_EXISTS_DELETE_ERROR);
        $list = DicGroup::query()->select(['id'])->whereIn('id', $ids)->limit(static::QUERY_LIMIT)->withCount('options')->get();
        abort_if($list->isEmpty(), ResponseEnum::DELETE_NOT_EXIST_ERROR);
        DB::transaction(function () use ($list) {
            foreach ($list as $row) {
                abort_if($row->options_count > 0, ResponseEnum::HTTP_ERROR, '存在字典项，不能删除');
                $row->delete();
                $this->createSyslog('删除了一条字典分类记录', [], $row);
            }
        });
        return $this->succeed();
    }
}
